import { DownOutlined, PlusOutlined, PaperClipOutlined } from '@ant-design/icons';
import { Button, Divider, Space, DatePicker, message, Select, TreeSelect } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';

import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import RectificationForm from './components/RectificationForm';
import { Link  ,useModel} from 'umi';
import { queryDefectRecord, updateDefectRecord, addDefectRecord,rectificationDefectRecord } from '@/services/defectrecord';
import { queryAreaTree } from '@/services/area';
import { userList } from '@/services/user';

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: any) => {
  const hide = message.loading('正在添加');
  try {
    await addDefectRecord(fields);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    await updateDefectRecord(fields);
    hide();

    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};


/**
 * 消缺
 * @param fields
 */
 const rectification = async (fields: any) => {
  const hide = message.loading('消缺中。。。');
  try {
    await rectificationDefectRecord(fields);
    hide();

    message.success('消缺成功');
    return true;
  } catch (error) {
    hide();
    message.error('消缺失败请重试！');
    return false;
  }
};

const TableList: React.FC<{}> = () => {
  const { initialState } = useModel('@@initialState');
  const { dicts } = initialState || {};
  const actionRef = useRef<ActionType>();
  const [userArray, setUserArray] = useState<API.UserItem[]>([]);
  const [areaData, setAreaData] = useState<API.TreeNodeItem[]>([]);
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  
  const [defectSourceEnumValues, setDefectSourceEnumValues] = useState({});
  const [rectificationModalVisible, handleRectificationModalVisible] = useState<boolean>(false);

  const [formValues, setFormValues] = useState({});

  const [enumSource, setEnumSource] = useState({});
  const [dicSource, setDicSource] = useState([]);

  const columns: ProColumns[] = [
    {
      title: '所在区域',
      dataIndex: 'areaName',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        return (
          <TreeSelect
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={areaData}
            placeholder="请选择所在区域"
            treeDefaultExpandAll
          />
        )
      },
    },
    {
      title: '设备名称',
      dataIndex: 'deviceName',
    },
    {
      title: '缺陷地点',
      dataIndex: 'location',
      hideInSearch: true,
    },
    {
      title: '缺陷内容',
      dataIndex: 'defect',
      search:false,
    },
    {
      title: '信息来源',
      dataIndex: 'defectSource',
      valueEnum: enumSource,
    },
    {
      title: '发现人',
      dataIndex: 'findName',
      hideInSearch: true,
    },
    {
      title: '发现时间',
      dataIndex: 'findTime',
      hideInSearch: true,
    },
    {
      title: '消缺人',
      dataIndex: 'eliminationName',
      hideInSearch: true,
    },
    {
      title: '消缺时间',
      dataIndex: 'defectEliminationTime',
      hideInSearch: true,
    },
    {
      title: '整改方案',
      dataIndex: 'rectificationPlan',
      width: '30%',
      hideInSearch: true,
    },
    {
      title: '操作',
      width: '10%',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            key="editable"
            onClick={async () => {
              handleUpdateModalVisible(true);
              console.log(record)
              setFormValues(record);
            }}
          >
            编辑
          </a>
          {!record.defectEliminationPerson?
          (<>
            <Divider type="vertical" />
            <a
              onClick={async () => {
                handleRectificationModalVisible(true);
                setFormValues(record);
              }}
            >消缺
            </a>
          </>):null}
        </>
      ),
    },
  ];

  const setStateData = async () => {
    let trees = await queryAreaTree();
    setAreaData(trees);
    const users = await userList();
    setUserArray(users);
    if (dicts) {
      setDicSource(dicts["5"]);
      setEnumSource(dicts["5Enum"]);
    }
  };

  useEffect(() => {
    setStateData();
  }, []);

  return (
    <>
      <ProTable
        headerTitle=""
        rowKey="defectId"
        actionRef={actionRef}
        tableAlertRender={false}
        toolBarRender={(action, { selectedRows }) => [
          <Button icon={<PlusOutlined />} type="primary" onClick={() => handleModalVisible(true)}>
            新增
          </Button>
        ]}
        toolbar={{
          settings: []
        }}
        search={{
          labelWidth: 'auto',
        }}
        rowSelection={{}}
        request={(params) => queryDefectRecord({ ...params })}
        columns={columns}
      />
      <CreateForm
        onSubmit={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            setFormValues({});
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        treeData={areaData}
        userData={userArray}
      />
      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleUpdateModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
          treeData={areaData}
          userData={userArray}
        />
      ) : null}
    {formValues && Object.keys(formValues).length ? (
        <RectificationForm
          onSubmit={async (value) => {
            value.defectId=formValues.defectId;
            const success = await rectification(value);
            if (success) {
              handleRectificationModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleRectificationModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={rectificationModalVisible}
          values={formValues}
       
        />
      ) : null}  


    </>
  );
};

export default TableList;
